<template>
  <div class="search-container">
    <form class="search-form"
          action="/">
      <van-search v-model="searchText"
                  background="#3296fa"
                  show-action
                  autofocus
                  placeholder="请输入搜索关键词"
                  @focus="isResultShow = false"
                  @search="onSearch"
                  @cancel="onCancel" />
    </form>
    <search-result v-if="isResultShow"
                   :search-text="searchText"></search-result>
    <search-suggestion v-else-if="searchText"
                       :search-text="searchText"
                       @search="onSearch"></search-suggestion>
    <search-history v-else
                    :search-history="searchHistory"
                    @clear-search-history="searchHistory = []"
                    @search="onSearch"></search-history>
  </div>
</template>

<script>
import SearchHistory from './components/search-history.vue'
import SearchSuggestion from './components/search-suggestion.vue'
import SearchResult from './components/search-result.vue'
import { setItem, getItem } from '@/utils/storage'
export default {
  components: {
    SearchHistory,
    SearchSuggestion,
    SearchResult
  },
  name: 'search',
  data () {
    return {
      searchText: '',
      isResultShow: false,
      searchHistory: getItem('TOUTIAO_SEARCH_HISTORY') || []
    }
  },
  watch: {
    searchHistory (value) {
      setItem('TOUTIAO_SEARCH_HISTORY', value)
    }
  },
  methods: {
    onSearch (val) {
      this.searchText = val
      // 1 不能重复 2 最新的放在最前面
      const index = this.searchHistory.indexOf(val)
      if (index !== -1) {
        this.searchHistory.splice(index, 1)
      }
      this.searchHistory.unshift(val)
      this.isResultShow = true
    },
    onCancel () {
      this.$router.back()
    }
  }
}
</script>

<style lang="less" scoped>
.search-container {
  padding-top: 108px;
  .van-search__action {
    color: #fff;
  }
  .search-form {
    position: fixed;
    top: 0;
    right: 0;
    left: 0;
    z-index: 1;
  }
}
</style>
